package com.lm.grizzly.component;

import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.NetworkListener;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class GrizzlyServerRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        HttpServer server = new HttpServer();
        NetworkListener listener = new NetworkListener("grizzly", "0.0.0.0", 8080);
        server.addListener(listener);

        // 注册一个简单的处理器
        server.getServerConfiguration().addHttpHandler(new HttpHandler() {
            @Override
            public void service(Request request, Response response) throws Exception {
                response.getWriter().write("Hello, Grizzly + Spring Boot 🚀");
            }
        }, "/hello");

        server.start();
        System.out.println("🚀 Grizzly started on http://localhost:8080/hello");

        Runtime.getRuntime().addShutdownHook(new Thread(server::shutdownNow));

        // ✅ 阻塞主线程，防止退出
        Thread.currentThread().join();
    }
}